<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\db\Query;
use think\Request;
use cmf\controller\AdminBaseController;
use app\admin\model\RoomModel;
use app\admin\model\SchoolModel;
use app\admin\model\LinkModel;


class RoomController extends AdminBaseController
{
    public function index()
    {
        $name=$this->request->param('name');
        $room =Db::name('room')
        ->join('cmf_school','cmf_school.id=cmf_room.school_id')
        ->field('cmf_school.name as school_name,cmf_room.*')
        ->where(function (Query $query) use ($name){
            if ($name){
                $query->where('cmf_room.name','like',"%$name%");
            }
        })
            ->order('id DESC')
            ->paginate(3,false,$this->request->param());
        $page=$room->render();
        return view('',['room'=>$room,'page'=>$page]);
    }
    public function add()
    {
        $school=SchoolModel::select();
        return $this->fetch('',['school'=>$school]);
    }
    public function addPost()
    {
        $data=input();
        if (empty($data['name'])){
            $this->error('班级名不能为空');
        }
        $add=RoomModel::create($data);
        if ($add){
            $this->success('添加成功','room/index');
        }else{
            $this->error('添加失败');
        }
    }

    public function edit()
    {
        $data=input();
        $room=RoomModel::get($data['id']);
        $school=SchoolModel::select();
        return view('',['room'=>$room,'school'=>$school]);
    }

    public function editPost()
    {
        $data=input();
        $edit=RoomModel::update($data,['id'=>$data['id']]);
        $hasRoom=Db::name('room')->where(['name'=>input('name')])->find();
        if ($hasRoom){
            $this->error('班级已经存在');
        }
        if ($edit){
            $this->success('修改成功','room/index');
        }else{
            $this->error('修改失败');
        }
    }
    public function delete($id)
    {
      $del=RoomModel::destroy($id);
      if ($del){
          $this->success('删除成功！','room/index');
      }else{
          $this->error('删除失败');
      }
    }
    public function delAll(){
        $ids=input('ids/a');
        $del=Db::name('room')->delete($ids);
        if ($del){
            return ['code'=>200,'msg'=>'删除成功'];
        }else{
            return ['code'=>100,'msg'=>'删除失败'];
        }
    }
}
